﻿using Microsoft.UI.Dispatching;
using Microsoft.Windows.AppLifecycle;
using Microsoft.Windows.AppNotifications;

namespace DimensionsHelper.Client.WinUi.Activation;

public class AppNotificationActivationHandler : ActivationHandler<LaunchActivatedEventArgs>
{
    private readonly INavigationService _navigationService;
    private readonly IAppNotificationService _notificationService;

    public AppNotificationActivationHandler(INavigationService navigationService,
        IAppNotificationService notificationService)
    {
        _navigationService = navigationService;
        _notificationService = notificationService;
    }

    protected override bool CanHandleInternal(LaunchActivatedEventArgs args) =>
        AppInstance.GetCurrent().GetActivatedEventArgs()?.Kind == ExtendedActivationKind.AppNotification;

    protected async override Task HandleInternalAsync(LaunchActivatedEventArgs args)
    {
        AppNotificationActivatedEventArgs activatedEventArgs =
            (AppNotificationActivatedEventArgs)AppInstance.GetCurrent().GetActivatedEventArgs().Data;
        NameValueCollection arguments = _notificationService.ParseArguments(activatedEventArgs.Argument);
        string? target = arguments["target"];

        if (!string.IsNullOrEmpty(target))
        {
            App.DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low, () =>
            {
                _navigationService.NavigateTo(target, arguments["detail"]);
            });

            await Task.CompletedTask;
        }
    }
}